<template>
    <XTable ref='tableRef' selection :api='devicePaginationApi' :columns='columns' @selectionChange='selectionChange'>
        <template #toolBar>
            <router-link to='/device/add/'>
                <el-button type='primary' size='mini'>新增</el-button>
            </router-link>
            <AllotMerchant :deviceIds='selectedDeviceIds' @success='reload' />
            <SetStrategy :deviceIds='selectedDeviceIds' @success='reload' />
        </template>

        <template #connectStatus='{row}'>
            {{row.connectStatus == 1 ? '在线' : '离线'}}
        </template>

        <template #action='{row}'>
            <template v-if='row'>
                <router-link :to='"/device/edit/" + row.deviceId'>
                    <el-button type='text'>编辑</el-button>
                </router-link>
                <router-link :to='"/device/" + row.deviceId'>
                    <el-button type='text'>详情</el-button>
                </router-link>
            </template>
        </template>
    </XTable>
</template>

<script lang='ts' setup>
    import { onActivated, reactive, ref } from 'vue'
    import AllotMerchant from './AllotMerchant.vue'
    import SetStrategy from './SetStrategy.vue'
    import { devicePaginationApi, toggledeviceStatusApi } from '../../api/device'
    import { ElMessage } from 'element-plus'
    import { Column } from '../../type'
import { useStore } from 'vuex'
    const $store = useStore()

    const columns:Column[] = [
        {title : '设备名', dataIndex : 'deviceName', inFilter : true},
        {title : '设备号', dataIndex : 'deviceId', inFilter : true},
        {title : '在线状态', dataIndex : 'connectStatus', inFilter : true}
    ]

    if($store.getters.isPlatform) {
        columns.push({title : '一级商户', dataIndex : 'merchantName'}, {title : '二级商户', dataIndex : 'subMerchantName'})
    }

    let selectedDeviceIds = reactive([])
    const tableRef = ref()
    const isFirst = ref(true)

    function selectionChange(rows:any[]) {
        selectedDeviceIds.splice(0)
        selectedDeviceIds.push(...rows.map(row => row.deviceId))
    }

    function reload() {
        tableRef.value.load()
    }

    onActivated(() => {
        if(isFirst.value) {
            isFirst.value = false
        }else {
            reload()
        }
    })

</script>